<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\model\JdHistory;
use app\model\JdUser;
use app\model\JdBeanRecord;

class GetBean extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\getbean')
            ->setDescription('the app\command\getbean command');
    }

    protected function execute(Input $input, Output $output)
    {
        $users = JdUser::select();
        foreach ($users as $key => $value) {
            if(!$value->cookie)
                continue;
            $this->getUserData($value, $output);
            $this->getYesterdayUserBeanBalanceDetail($value, $output);
        }
    }

    protected function getUserData(JdUser $jduser, Output $output)
    {
        $this->getTotalBean($jduser, $output);
    }

    protected function getYesterdayUserBeanBalanceDetail(JdUser $jduser, Output $output)
    {
        $amonthago = strtotime(date("Y-m-d",strtotime("-1 month")));
        $yesterday = strtotime(date("Y-m-d",strtotime("-1 day")));
        $today = strtotime(date("Y-m-d"));
        $first = JdBeanRecord::where('uid', $jduser->id)->count() == 0;
        $count = JdBeanRecord::where('uid', $jduser->id)
            ->where('datetime', '>=', date("Y-m-d H:i:s", $yesterday))
            ->where('datetime','<', date("Y-m-d H:i:s", $today))
            ->count();
    
        if($count == 0) {
            $t = 0;
            $page = 1;
            $reocdtosave = [];
            do {
                $data = $this->getJingBeanBalanceDetail($page, $jduser, $output);

                if($data->code === '0') {
                    $output->writeln("获取用户京豆列表成功：{$jduser->id} {$jduser->pt_pin} page={$page}, count=" . count($data->detailList));
                    $page++;
                    if(count($data->detailList) > 0) {
                        foreach ($data->detailList as $key => $value) {
                            // {
                            //     "date": "2020-12-15 12:05:45",
                            //     "amount": "1",
                            //     "eventMassage": "东东农场转盘抽奖活动"
                            // },
                            $time = strtotime($value->date);
                            if($time > $today){
                                continue;
                            }
                            if($time < $yesterday) {
                                // 首次导入一个月数据
                                if(!$first || $time < $amonthago) {
                                    $t = 1;
                                    break;
                                }
                            }

                            $record = new JdBeanRecord();
                            $record->uid = $jduser->id;
                            $record->account = $jduser->pt_pin;
                            $record->datetime = $value->date;
                            $record->amount = $value->amount;
                            $record->event_message = $value->eventMassage;
                            // $record->save();
                            $reocdtosave[] = $record;
                        }
                    } else {
                        $t = 1;
                    }
                } else {
                    $output->writeln("获取用户京豆数据异常：{$jduser->pt_pin} page={$page}, code={$data->code}");
                    $t = 1;
                }
            } while($t == 0);
            // 读取的数据是倒序的，所以这里倒过来保存
            $recordCount = count($reocdtosave);
            if($recordCount > 0) {
                for ($i= $recordCount - 1 ; $i >=0 ; $i--) { 
                    $reocdtosave[$i]->save();
                    if($i % 10 == 0) {
                        $current = $recordCount - $i;
                        $output->writeln("保存数据 $current / $recordCount");
                    }
                }
            }
        }

        if(!$first) {
            $this->insertHistory(date('Y-m-d',$yesterday), $jduser);
        } else {
            for ($i=30; $i >= 1; $i--) { 
                $start = date('Y-m-d', strtotime("-$i day", $today));
                $this->insertHistory($start, $jduser);
            }
        }
    }

    protected function insertHistory($date, $jduser) {
        
        $count = JdHistory::where('uid', $jduser->id)
            ->where('date', $date)
            ->count();
        $end = date('Y-m-d',strtotime('+1 day',strtotime($date)));
        if($count == 0) {
            $increaseSum = JdBeanRecord::where('uid', $jduser->id)
                ->where('datetime', '>=', $date)
                ->where('datetime','<', $end)
                ->where('amount', '>', 0)
                ->sum('amount');
            $decreaseSum = JdBeanRecord::where('uid', $jduser->id)
                ->where('datetime', '>=', $date)
                ->where('datetime','<', $end)
                ->where('amount', '<', 0)
                ->sum('amount');
            $history = new JdHistory();
            $history->uid = $jduser->id;
            $history->account = $jduser->pt_pin;
            $history->date = $date;
            $history->increase = $increaseSum;
            $history->decrease = $decreaseSum;
            $history->total = $jduser->bean_total;
            $history->save();
            echo "insert JdHistory $jduser->nickname $date\n";
        }
    }

    protected function getTotalBean(JdUser $user, Output $output) {
        $headers = [
            'User-Agent: jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0',
            'Accept: application/json,text/plain, */*',
            'Content-Type: application/x-www-form-urlencoded',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: zh-cn',
            'Connection: keep-alive',
            'Referer: https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2'
        ];
        try {
            $response = $this->curl_post('https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2', 
                [], 
                $user->cookie,
                $headers
            );
            if($response) {
                $data = json_decode($response);
                if($data->retcode == 0) {
                    $user->nickname = $data->base->nickname;
                    $user->mobile = $data->base->mobile;
                    $user->pt_pin = $data->base->curPin;
                    $user->bean_total = $data->base->jdNum;
                    $user->save();
                    $output->writeln("获取用户总京豆成功：{$user->pt_pin} 总京豆：{$user->bean_total}");
                }
                if($data->retcode == 13) {
                    $user->expired = 1;
                    $user->save();
                    $output->writeln("用户Cookie过期：{$user->pt_pin} {$user->mobile}");
                }
            } else {
                $output->writeln("获取用户总京豆出错：{$user->id} {$user->pt_pin}");
            }
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用户总京豆出错：{$user->id} {$user->pt_pin} {$th}");
        }
       
        // $output->writeln('QueryJDUserInfo body = ' . $response);
        // {
        //     "base" : {
        //        "TipUrl" : "http://wqs.jd.com/my/accountv2.shtml?sceneid=11110&state=0&rurl=https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2",
        //        "accountType" : 0,
        //        "curPin" : "153919351_m",
        //        "headImageUrl" : "",
        //        "isJTH" : "0",
        //        "jdNum" : 1230,
        //        "jvalue" : 5792,
        //        "levelName" : "银牌用户",
        //        "mobile" : "138*****667",
        //        "nickname" : "153919351",
        //        "userLevel" : 61
        //     },
        //     "definePin" : 0,
        //     "isHitArea" : 0,
        //     "isHomeWhite" : 0,
        //     "isLongPwdActive" : 0,
        //     "isPlusVip" : false,
        //     "isRealNameAuth" : true,
        //     "isShortPwdActive" : 1,
        //     "msg" : "success.",
        //     "orderFlag" : 1,
        //     "retcode" : 0,
        //     "userFlag" : 1
        //  }
        return true;
    }

    protected function getJingBeanBalanceDetail(int $page, JdUser $user, Output $output) {
         $headers = [
            'User-Agent: jdapp;iPhone;9.2.2;14.2;%E4%BA%AC%E4%B8%9C/9.2.2 CFNetwork/1206 Darwin/20.1.0',
            'Accept: application/json,text/plain, */*',
            'Content-Type: application/x-www-form-urlencoded',
            'Host: api.m.jd.com',
            'Accept-Language: zh-cn'
        ];
        $pageinfo = new \StdClass();
        $pageinfo->pageSize = "20";
        $pageinfo->page = "$page";

        try {
            $response = $this->curl_post('https://api.m.jd.com/client.action?functionId=getJingBeanBalanceDetail', 
                [
                    'body' => json_encode($pageinfo),
                    'appid' => 'ld'
                ], 
                $user->cookie,
                $headers,
                false
            );
            // $output->writeln('getJingBeanBalanceDetail body = ' . $response);
            
            return json_decode($response);
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用户京豆列表出错：{$user->id} {$user->pt_pin} {$th}");
            return new \StdClass();
        }
        
        // sample
        // {
        //     "code": "0",
        //     "detailList": [
        //         {
        //             "date": "2020-12-15 12:05:45",
        //             "amount": "1",
        //             "eventMassage": "东东农场转盘抽奖活动"
        //         },
        //         {
        //             "date": "2020-12-15 11:20:02",
        //             "amount": "5",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:20:01",
        //             "amount": "1",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:15:02",
        //             "amount": "5",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:15:01",
        //             "amount": "1",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:11:40",
        //             "amount": "5",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:11:40",
        //             "amount": "1",
        //             "eventMassage": "京豆"
        //         },
        //         {
        //             "date": "2020-12-15 11:00:01",
        //             "amount": "8",
        //             "eventMassage": "红包雨京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:17",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:16",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:15",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:14",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:12",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:11:11",
        //             "amount": "1",
        //             "eventMassage": "今日王牌领京豆"
        //         },
        //         {
        //             "date": "2020-12-15 09:00:03",
        //             "amount": "8",
        //             "eventMassage": "红包雨京豆"
        //         },
        //         {
        //             "date": "2020-12-15 08:40:11",
        //             "amount": "10",
        //             "eventMassage": "京东秒杀红包雨活动奖励"
        //         },
        //         {
        //             "date": "2020-12-15 08:40:06",
        //             "amount": "10",
        //             "eventMassage": "京东秒杀红包雨活动奖励"
        //         },
        //         {
        //             "date": "2020-12-15 08:40:01",
        //             "amount": "10",
        //             "eventMassage": "京东秒杀红包雨活动奖励"
        //         },
        //         {
        //             "date": "2020-12-15 08:36:01",
        //             "amount": "2",
        //             "eventMassage": "签到领豆"
        //         },
        //         {
        //             "date": "2020-12-15 06:06:08",
        //             "amount": "10",
        //             "eventMassage": "东东农场转盘抽奖活动"
        //         }
        //     ]
        // }
    }

    function curl_post($url , $data=array(), $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }
}
